<?php

namespace app\admin\command;

use app\admin\model\User;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;


class Share extends Command
{
    protected function configure()
    {
        $this->setName('Share')->setDescription("计划任务 Share");
    }

    protected function execute(Input $input, Output $output)
    {
        $output->writeln('Date Crontab job start...');
        /*** 这里写计划任务列表集 START ***/

        $this->Share();
       
        /*** 这里写计划任务列表集 END ***/
        $output->writeln('Date Crontab job end...');
    }

    // 获取昨天实际支付订单
    private function Share()
    {
        //获取昨日起始时间和结束时间
        $beginYesterday = date('Y-m-d 00:00:00', strtotime('-1 day'));
        $endYesterday = date('Y-m-d 00:00:00');
        $orders =  Db::connect('database_b')->table('orders')
            ->whereTime('pay_time', 'between', [$beginYesterday, $endYesterday])
            ->where(['pay_status' => 1, 'is_sign'=>0])->select();
        foreach ($orders as $key => $value) {
            // 找该用户的 二级分销商 和 一级分销商
            $this->getsuperior($value['uid']);
            // 更新
            Db::connect('database_b')->table('orders')->where('id',$value['id'])->update(['is_sign'=>1]);
        }
        echo date("Y-m-d H:i:s") . " 成功 \r\n";
    }

    private function getsuperior($user_id)
    {
        $fttuser = Db::connect('database_b')->table('fttuser')->where('share_level', 'in', array(1,2))->where(['user_id' => $user_id])->find();
        if (!empty($fttuser)) {
            return 0;
        } else {
            $arr_parent = $this->get_witch_role($user_id);
            if ($arr_parent['user_id'] == 0) {
                return 0;
            }
            if ($arr_parent['role'] == 1) { // 如果是一级分销商直接分钱
                $this->addDate($arr_parent['user_id'], 1, $user_id);
            } else { // 如果是二级分销商直接分钱 找到最近的一级分销商 
                $this->addDate($arr_parent['user_id'], 2, $user_id);
                $one_parent_id = $this->get_one_role($arr_parent['user_id']);
                if ($one_parent_id != 0) { // 给一级分销商分钱
                    $this->addDate($one_parent_id, 1, $user_id);
                }
            }
        }
    }

    /**
     * 递归查找最近的上级是二级分销商 或者一级分销商
     */
    private  function get_witch_role($user_id, $arr = array())
    {
        if (empty($arr) && count($arr) != count(array_unique($arr))) {
            return array('user_id' => 0, 'role' => 0);
        }
        //判断该用户是否是二级分销商 或者一级分销商 
        $shareWitch = Db::connect('database_b')->table('fttuser')->where(['user_id' => $user_id])->find();
        if (empty($shareWitch)) {
            return array('user_id' => 0, 'role' => 0);
        }
        if (!empty($shareWitch) && in_array($shareWitch['share_level'], array(1,2))) {
            return array('user_id' => $user_id, 'role' => $shareWitch['share_level']);
        } else {
            $arr[] = $shareWitch['parent_user_id'];
            return $this->get_witch_role($shareWitch['parent_user_id'], $arr);
        }
    }

    /**
     * 递归查找最近的上级一级分销商
     */
    private  function get_one_role($user_id, $arr = array())
    {
        if (empty($arr) && count($arr) != count(array_unique($arr))) {
            return 0;
        }
        //判断该用户是否是一级分销商
        $shareWitch = Db::connect('database_b')->table('fttuser')->where(['user_id' => $user_id])->find();
        if (empty($shareWitch)) {
            return 0;
        }
        if (!empty($shareWitch) && $shareWitch['share_level'] == 1) {
            return $user_id;
        } else {
            $arr[] = $shareWitch['parent_user_id'];
            return $this->get_one_role($shareWitch['parent_user_id'], $arr);
        }
    }

    /**
     * 添加数据
     */
    private function addDate($parent_user_id, $role, $user_id)
    {
        $total = ($role == 2) ? 245 : 294;
        $account =  Db::connect('database_b')->table('account')->where(['acctc' => 'teamProfit','drcrbal' => 'bal', 'user_id' => $parent_user_id ])->find();
        if (empty($account)) {
            $total1 = $total;
            Db::connect('database_b')->table('account')->insert([
                'created_at' => date("Y-m-d H:i:s"),
                'acctc' => 'teamProfit', // 科目
                'drcrbal' => 'bal', // 符号: incr(增);decr(减)
                'total' => $total1, // 
                'user_id' => $parent_user_id 
            ]);
        } else {
            $total1 = bcadd($account['total'], $total, 2);
            Db::connect('database_b')->table('account')->where('id',$account['id'])->update(['total' => $total1,'updated_at' => date("Y-m-d H:i:s")]);
        }

        $account1 =  Db::connect('database_b')->table('account')->where(['acctc' => 'pinmoney','drcrbal' => 'bal', 'user_id' => $parent_user_id ])->find();
        if (empty($account1)) {
            $total2 = $total;
            Db::connect('database_b')->table('account')->insert([
                'created_at' => date("Y-m-d H:i:s"),
                'acctc' => 'pinmoney', // 科目
                'drcrbal' => 'bal', // 符号: incr(增);decr(减)
                'total' => $total2, // 
                'user_id' => $parent_user_id 
            ]);
        } else {
            $total2 = bcadd($account1['total'], $total, 2);
            Db::connect('database_b')->table('account')->where('id',$account1['id'])->update(['total' => $total2,'updated_at' => date("Y-m-d H:i:s")]);
        }
       
        Db::connect('database_b')->table('accountitem')->insert([
            'created_at' => date("Y-m-d H:i:s"),
            'acctc' => 'pinmoney', // 科目
            'drcr' => 'incr', // 符号: incr(增);decr(减)
            'name' => '团队分红', 
            'value' => $total, // 交易额
            'balance' => 0, // 交易后余额
            'another_user_id' => 0, // 对方用户ID
            'rel_type' => 'pinmoney', //关联类型   
            'rel_id' => $parent_user_id,//关联目标
            'period_month' => date('Y').date('m'),//账期月份
            'period_day' => date('Ymd'),//账期日期
            'user_id' => $parent_user_id
        ]);

        Db::connect('database_b')->table('accountitem')->insert([
            'created_at' => date("Y-m-d H:i:s"),
            'acctc' => 'teamProfit', // 科目
            'drcr' => 'incr', // 符号: incr(增);decr(减)
            'name' => '团队分红', 
            'value' => $total, // 交易额
            'balance' => 0, // 交易后余额
            'another_user_id' => 0, // 对方用户ID
            'rel_type' => 'teamProfit', //关联类型   
            'rel_id' => $parent_user_id,//关联目标
            'period_month' => date('Y').date('m'),//账期月份
            'period_day' => date('Ymd'),//账期日期
            'user_id' => $parent_user_id
        ]);

        echo "订单用户ID：" . $user_id . "； 分销商用户ID：" . $parent_user_id . "；分销商等级：" . $role . "\r\n";
    }
}
